home *** CD-ROM | disk | FTP | other *** search
/ American Osteopathic Ass…tion Yearbook 2005 & 2006 / American Osteopathic Association Yearbook 2005 & 2006.iso / mac / app / popen2.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2004-07-22  |  9.5 KB  |  243 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.3)
  3.  
  4. """Spawn a command with pipes to its stdin, stdout, and optionally stderr.
  5.  
  6. The normal os.popen(cmd, mode) call spawns a shell command and provides a
  7. file interface to just the input or output of the process depending on
  8. whether mode is 'r' or 'w'.  This module provides the functions popen2(cmd)
  9. and popen3(cmd) which return two or three pipes to the spawned command.
  10. """
  11. import os
  12. import sys
  13. __all__ = [
  14.     'popen2',
  15.     'popen3',
  16.     'popen4']
  17. MAXFD = 256
  18. _active = []
  19.  
  20. def _cleanup():
  21.     for inst in _active[:]:
  22.         inst.poll()
  23.     
  24.  
  25.  
  26. class Popen3:
  27.     '''Class representing a child process.  Normally instances are created
  28.     by the factory functions popen2() and popen3().'''
  29.     sts = -1
  30.     
  31.     def __init__(self, cmd, capturestderr = False, bufsize = -1):
  32.         """The parameter 'cmd' is the shell command to execute in a
  33.         sub-process.  The 'capturestderr' flag, if true, specifies that
  34.         the object should capture standard error output of the child process.
  35.         The default is false.  If the 'bufsize' parameter is specified, it
  36.         specifies the size of the I/O buffers to/from the child process."""
  37.         _cleanup()
  38.         (p2cread, p2cwrite) = os.pipe()
  39.         (c2pread, c2pwrite) = os.pipe()
  40.         if capturestderr:
  41.             (errout, errin) = os.pipe()
  42.         
  43.         self.pid = os.fork()
  44.         if self.pid == 0:
  45.             os.dup2(p2cread, 0)
  46.             os.dup2(c2pwrite, 1)
  47.             if capturestderr:
  48.                 os.dup2(errin, 2)
  49.             
  50.             self._run_child(cmd)
  51.         
  52.         os.close(p2cread)
  53.         self.tochild = os.fdopen(p2cwrite, 'w', bufsize)
  54.         os.close(c2pwrite)
  55.         self.fromchild = os.fdopen(c2pread, 'r', bufsize)
  56.         if capturestderr:
  57.             os.close(errin)
  58.             self.childerr = os.fdopen(errout, 'r', bufsize)
  59.         else:
  60.             self.childerr = None
  61.         _active.append(self)
  62.  
  63.     
  64.     def _run_child(self, cmd):
  65.         if isinstance(cmd, basestring):
  66.             cmd = [
  67.                 '/bin/sh',
  68.                 '-c',
  69.                 cmd]
  70.         
  71.         for i in range(3, MAXFD):
  72.             
  73.             try:
  74.                 os.close(i)
  75.             continue
  76.             except OSError:
  77.                 continue
  78.             
  79.  
  80.         
  81.         
  82.         try:
  83.             os.execvp(cmd[0], cmd)
  84.         finally:
  85.             os._exit(1)
  86.  
  87.  
  88.     
  89.     def poll(self):
  90.         """Return the exit status of the child process if it has finished,
  91.         or -1 if it hasn't finished yet."""
  92.         if self.sts < 0:
  93.             
  94.             try:
  95.                 (pid, sts) = os.waitpid(self.pid, os.WNOHANG)
  96.                 if pid == self.pid:
  97.                     self.sts = sts
  98.                     _active.remove(self)
  99.             except os.error:
  100.                 pass
  101.             except:
  102.                 None<EXCEPTION MATCH>os.error
  103.             
  104.  
  105.         None<EXCEPTION MATCH>os.error
  106.         return self.sts
  107.  
  108.     
  109.     def wait(self):
  110.         '''Wait for and return the exit status of the child process.'''
  111.         if self.sts < 0:
  112.             (pid, sts) = os.waitpid(self.pid, 0)
  113.             if pid == self.pid:
  114.                 self.sts = sts
  115.                 _active.remove(self)
  116.             
  117.         
  118.         return self.sts
  119.  
  120.  
  121.  
  122. class Popen4(Popen3):
  123.     childerr = None
  124.     
  125.     def __init__(self, cmd, bufsize = -1):
  126.         _cleanup()
  127.         (p2cread, p2cwrite) = os.pipe()
  128.         (c2pread, c2pwrite) = os.pipe()
  129.         self.pid = os.fork()
  130.         if self.pid == 0:
  131.             os.dup2(p2cread, 0)
  132.             os.dup2(c2pwrite, 1)
  133.             os.dup2(c2pwrite, 2)
  134.             self._run_child(cmd)
  135.         
  136.         os.close(p2cread)
  137.         self.tochild = os.fdopen(p2cwrite, 'w', bufsize)
  138.         os.close(c2pwrite)
  139.         self.fromchild = os.fdopen(c2pread, 'r', bufsize)
  140.         _active.append(self)
  141.  
  142.  
  143. if sys.platform[:3] == 'win' or sys.platform == 'os2emx':
  144.     del Popen3
  145.     del Popen4
  146.     
  147.     def popen2(cmd, bufsize = -1, mode = 't'):
  148.         """Execute the shell command 'cmd' in a sub-process.  If 'bufsize' is
  149.         specified, it sets the buffer size for the I/O pipes.  The file objects
  150.         (child_stdout, child_stdin) are returned."""
  151.         (w, r) = os.popen2(cmd, mode, bufsize)
  152.         return (r, w)
  153.  
  154.     
  155.     def popen3(cmd, bufsize = -1, mode = 't'):
  156.         """Execute the shell command 'cmd' in a sub-process.  If 'bufsize' is
  157.         specified, it sets the buffer size for the I/O pipes.  The file objects
  158.         (child_stdout, child_stdin, child_stderr) are returned."""
  159.         (w, r, e) = os.popen3(cmd, mode, bufsize)
  160.         return (r, w, e)
  161.  
  162.     
  163.     def popen4(cmd, bufsize = -1, mode = 't'):
  164.         """Execute the shell command 'cmd' in a sub-process.  If 'bufsize' is
  165.         specified, it sets the buffer size for the I/O pipes.  The file objects
  166.         (child_stdout_stderr, child_stdin) are returned."""
  167.         (w, r) = os.popen4(cmd, mode, bufsize)
  168.         return (r, w)
  169.  
  170. else:
  171.     
  172.     def popen2(cmd, bufsize = -1, mode = 't'):
  173.         """Execute the shell command 'cmd' in a sub-process.  If 'bufsize' is
  174.         specified, it sets the buffer size for the I/O pipes.  The file objects
  175.         (child_stdout, child_stdin) are returned."""
  176.         inst = Popen3(cmd, False, bufsize)
  177.         return (inst.fromchild, inst.tochild)
  178.  
  179.     
  180.     def popen3(cmd, bufsize = -1, mode = 't'):
  181.         """Execute the shell command 'cmd' in a sub-process.  If 'bufsize' is
  182.         specified, it sets the buffer size for the I/O pipes.  The file objects
  183.         (child_stdout, child_stdin, child_stderr) are returned."""
  184.         inst = Popen3(cmd, True, bufsize)
  185.         return (inst.fromchild, inst.tochild, inst.childerr)
  186.  
  187.     
  188.     def popen4(cmd, bufsize = -1, mode = 't'):
  189.         """Execute the shell command 'cmd' in a sub-process.  If 'bufsize' is
  190.         specified, it sets the buffer size for the I/O pipes.  The file objects
  191.         (child_stdout_stderr, child_stdin) are returned."""
  192.         inst = Popen4(cmd, bufsize)
  193.         return (inst.fromchild, inst.tochild)
  194.  
  195.     __all__.extend([
  196.         'Popen3',
  197.         'Popen4'])
  198.  
  199. def _test():
  200.     cmd = 'cat'
  201.     teststr = 'ab cd\n'
  202.     if os.name == 'nt':
  203.         cmd = 'more'
  204.     
  205.     expected = teststr.strip()
  206.     print 'testing popen2...'
  207.     (r, w) = popen2(cmd)
  208.     w.write(teststr)
  209.     w.close()
  210.     got = r.read()
  211.     if got.strip() != expected:
  212.         raise ValueError('wrote %s read %s' % (`teststr`, `got`))
  213.     
  214.     print 'testing popen3...'
  215.     
  216.     try:
  217.         (r, w, e) = popen3([
  218.             cmd])
  219.     except:
  220.         (r, w, e) = popen3(cmd)
  221.  
  222.     w.write(teststr)
  223.     w.close()
  224.     got = r.read()
  225.     if got.strip() != expected:
  226.         raise ValueError('wrote %s read %s' % (`teststr`, `got`))
  227.     
  228.     got = e.read()
  229.     if got:
  230.         raise ValueError('unexected %s on stderr' % `got`)
  231.     
  232.     for inst in _active[:]:
  233.         inst.wait()
  234.     
  235.     if _active:
  236.         raise ValueError('_active not empty')
  237.     
  238.     print 'All OK'
  239.  
  240. if __name__ == '__main__':
  241.     _test()
  242.  
  243.